from django.shortcuts import render,render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
from django.contrib import auth
from django.template.context import RequestContext
from django.contrib.auth.decorators import login_required
from django.core.cache import cache
from .models import UserProfile, u_permissions, u_user_permission
from datetime import datetime
from configparser import ConfigParser
from audit.models import a_aduit_data, a_user_rule

import random
import string
import traceback
import json
import os
import time

config_file = r'conf\config.ini'
config = ConfigParser()
config.read(config_file,encoding='utf-8')

@login_required(login_url='/login')
def index(request):
    username = request.user
    userid = User.objects.get(username=username).id
    permissing = UserProfile.objects.get(user_id=userid).permissions_page
    permmiss_list = u_user_permission.objects.filter(u_id=userid).values_list('p_level')
    logo_name1 = UserProfile.objects.get(user_id=userid).name
    logo_name2 = "\"" + logo_name1 + "\""
    page_list = []
    if permissing == "all":
        for i in u_permissions.objects.all().values_list('permissions_level'):
            page_list.append(i[0])
        page_list.append(9)
    elif permissing == "9":
        page_list.append(9)

    else:
        # page_list = permissing.split(',')
        for i in permmiss_list:
            if int(i[0]) == 8:
                page_list.append(9)
            else:
                page_list.append(i[0])
    try:
        level_id = a_user_rule.objects.filter(username=username).values_list('rule_id')[0][0]
    except:
        level_id=0
    return render(request, 'base.html', {"page_list": page_list, "logo_name": logo_name2, "level_id":level_id})

@csrf_exempt
def useraudit(request):
    if request.is_ajax():
        if request.method == 'POST':
            alevel = int(request.POST.get('level'))
            _status = 1
            num = 0
            try:
                num = a_aduit_data.objects.filter(process=alevel,status=0,is_delete=0).count()
                _status = 0
            except BaseException as b:
                _log_err = "useraudit 函数报错 --》" + str(b)
                print(_log_err)
            finally:
                return HttpResponse(json.dumps({'status':_status, "number":num}))

@csrf_exempt
def login(request):
    # adduser()
    l_session = Sign_On()
    _status = 1
    if request.user.is_authenticated():
        return HttpResponseRedirect("/index/")
    if request.method == 'POST':
        username = request.POST.get("username")
        password = request.POST.get("password")
        keeppwd = request.POST.get("keeppwd")
        userauth = auth.authenticate(username=username, password=password)
        print(keeppwd)
        if userauth is not None:
            if userauth.is_active:
                print('登陆成功！！！！！！！！！！')
                auth.login(request, userauth)
                l_session.del_session(request.user)
                l_session.add_session(request.user, request.session.session_key)
                print(request.user, request.session.session_key, 222222222)
                response = HttpResponseRedirect('/index/')
                if keeppwd == "on":
                    response.set_cookie('userName',username)
                    response.set_cookie('passWord',password )
                return response
            else:
                print('用户被禁用')
                _status = 2
        else:
            print('用户密码错误')
            _status = 3
    return render(request, 'users/login.html', {"status": _status})

@csrf_exempt
@login_required(login_url='/login')
def logout(request):
    auth.logout(request)
    print("成功退出当前用户")
    return HttpResponse({'status':0})

#单点登陆机制
class Sign_On(object):
    def __init__(self):
        pass
    def del_session(self, username):
        session_key = cache.get(username)
        print(username, session_key)
        if session_key != None:
            key_name = 'django.contrib.sessions.cache' + session_key
            cache.delete(key_name)
            print('删除%s用户上一个登陆session' % username)
    def add_session(self, username, session_key):
        print(username,session_key)
        cache.set(username, session_key, timeout=288000)

@login_required(login_url='/login')
def management(request):
    m_rule_list = rule_data()
    m_user_list = user_data()
    return render(request, 'users/management.html', {"user_list":json.dumps(m_user_list), "rule_list": json.dumps(m_rule_list)})

def user_data():
    ud_user_list = []
    ud_user_data = User.objects.values('id', 'username', 'email', 'is_active', 'password')
    ud_user_other_data = UserProfile.objects.filter(is_delete=0).values('user_id', 'name', 'permissions_page')
    for ud_u in ud_user_data:
        ud_user_json = {}
        for ud_o in ud_user_other_data:
            if ud_u["id"] == ud_o["user_id"]:
                ud_user_json["uid"] = ud_u["id"]
                ud_user_json["name"] = ud_o["name"]
                ud_user_json["username"] = ud_u["username"]
                ud_user_json["email"] = ud_u["email"]
                if ud_o["permissions_page"] == "all":
                    ud_user_json["permissions_page"] = ud_o["permissions_page"]
                else:
                    p_list = u_user_permission.objects.filter(u_id=int(ud_u["id"])).values_list('p_level')
                    plist=[]
                    for i in p_list:
                        plist.append(str(i[0]))
                    ud_user_json["permissions_page"] = ','.join(plist)
                # ud_user_json["permissions_page"] = ud_o["permissions_page"]
                if ud_u["is_active"]:
                    ud_user_json["is_using"] = 1
                else:
                    ud_user_json["is_using"] = 0
                ud_user_list.append(ud_user_json)
    return ud_user_list

def rule_data():
    rd_rule_list = []
    rd_rule_data = u_permissions.objects.filter(is_delete=0).values('permissions_level', 'describe')
    for rd_r in rd_rule_data:
        rd_rule_json = {}
        rd_rule_json["permissions"] = rd_r["permissions_level"]
        rd_rule_json["describe"] = rd_r["describe"]
        rd_rule_list.append(rd_rule_json)
    return rd_rule_list

@csrf_exempt
def useropt(request):
    if request.is_ajax():
        if request.method == 'POST':
            uo_type = int(request.POST.get('type'))
            land = Sign_On()
            uo_return_status = 1
            if uo_type == 0:
                try:
                    uo_status = int(request.POST.get('status'))
                    uo_id = int(request.POST.get('id'))
                    User.objects.filter(id=uo_id).update(is_active=uo_status)
                    uo_username = User.objects.filter(id=uo_id).values_list('username')[0][0]
                    land.del_session(uo_username)
                    uo_return_status = 0
                except:
                    uo_return_status = 1
                finally:
                    return HttpResponse(json.dumps({'status': uo_return_status}))
            elif uo_type == 1:
                pass
            elif uo_type == 2:
                uo_id = int(request.POST.get('id'))
                User.objects.filter(id=uo_id).update(is_active=0)
                UserProfile.objects.filter(user_id=uo_id).update(is_delete=1)
                uo_data = user_data()
                return HttpResponse(json.dumps({'data': uo_data}))
            else:
                return HttpResponse(json.dumps({'status': uo_return_status}))

def u_rule_mod(uid,plist):
    op_list = u_user_permission.objects.filter(u_id=uid).values_list('p_level')
    for i in op_list:
        if str(i[0]) not in plist:
            u_user_permission.objects.filter(u_id=uid,p_level=i[0]).update(is_delete=1)
        else:
            plist.remove(str(i[0]))
            u_user_permission.objects.filter(u_id=uid, p_level=i[0]).update(is_delete=0)
    for y in plist:
        u_user_permission.objects.create(u_id=uid,p_level=int(y))





@csrf_exempt
def useroptam(request):
    if request.is_ajax():
        if request.method == "POST":
            uone = ['name', 'permissions_page', 'user_id']
            uom_type = int(request.POST.get("type"))
            uom_status = 1
            land = Sign_On()
            if uom_type == 0:
                uom_data = eval(request.POST.get("data"))
                uom_id = uom_data["user_id"]
                uom_data.pop('user_id')
                uom_one_json = {}
                uom_two_json = {}
                try:
                    for uom_k, uom_v in uom_data.items():
                        if uom_k in uone:
                            if uom_k == "permissions_page":
                                p_list = uom_v.split(',')
                                u_rule_mod(uom_id, p_list)
                            else:
                                uom_one_json[uom_k] = uom_v
                        else:
                            if uom_k == "password":
                                uom_user = User.objects.get(id=uom_id)
                                uom_user.set_password(uom_v)
                                uom_user.save()

                            else:
                                uom_two_json[uom_k] = uom_v
                    UserProfile.objects.filter(user_id=uom_id).update(**uom_one_json)
                    User.objects.filter(id=uom_id).update(**uom_two_json)
                    uom_username = User.objects.filter(id=uom_id).values_list('username')[0][0]
                    land.del_session(uom_username)
                    uom_status = 0
                except BaseException as b:  # 所有异常的基类
                    print('useroptam traceback.print_exc(): %s' % traceback.print_exc())  # 最详细
                    uom_status = 1
                finally:
                    uom_data = user_data()
                    return HttpResponse(json.dumps({'data':uom_data, 'status':uom_status}))
            elif uom_type == 1:
                try:
                    uom_data = eval(request.POST.get("data"))
                    uom_user = User.objects.create_user(username=uom_data["username"], password=uom_data["password"], email=uom_data["email"])
                    uom_user.save()
                    profile = UserProfile()
                    profile.user_id = uom_user.id
                    profile.name = uom_data["name"]
                    # profile.permissions_page = uom_data["permissions_page"]
                    profile.save()
                    p_list = uom_data["permissions_page"].split(',')
                    for uom_i in p_list:
                        u_user_permission.objects.create(u_id=int(uom_user.id), p_level=int(uom_i))
                    uom_status = 0
                except:
                    uom_status = 1
                finally:
                    uom_data = user_data()
                    return HttpResponse(json.dumps({'data':uom_data, 'status':uom_status}))

@csrf_exempt
def ruleopt(request):
    if request.is_ajax():
        if request.method == 'POST':
            ro_type = int(request.POST.get('type'))
            ro_status = 1
            if ro_type == 0:
                ro_retrun_data = None
                try:
                    ro_optid = int(request.POST.get('data'))
                    u_permissions.objects.filter(permissions_level=ro_optid).update(is_delete=1)
                    ro_retrun_data = rule_data()
                    ro_status = 0
                except:
                    ro_status = 1
                finally:
                    return HttpResponse(json.dumps({'data':ro_retrun_data, 'status':ro_status}))
            elif ro_type == 1:
                ro_retrun_data = None
                try:
                    ro_optid = int(request.POST.get('ruleid'))
                    ro_optdes = request.POST.get('describe')
                    old_data = u_permissions.objects.filter(permissions_level=ro_optid, is_delete=0)
                    if len(old_data) == 0:
                        u_permissions.objects.create(permissions_level=ro_optid, describe=ro_optdes, is_delete=0)
                        ro_retrun_data = rule_data()
                        ro_status = 0
                    else:
                        ro_status = 2
                except:
                    ro_status = 1
                finally:
                    return HttpResponse(json.dumps({'data':ro_retrun_data, 'status':ro_status}))
            else:
                return HttpResponse({'status': ro_status})


def details(request):
    username = request.user
    d_data_list = one_user_data(username)
    return render(request, 'users/details.html', {'data':json.dumps(d_data_list)})

def one_user_data(uname):
    d_o_data = list(User.objects.filter(username=uname).values_list('id','email','date_joined')[0])
    d_t_data = UserProfile.objects.filter(user_id=d_o_data[0]).values_list('name', 'imgfile')[0]
    d_o_data[2] = d_o_data[2].strftime('%Y/%m/%d %H:%M:%S')
    for d_i in d_t_data:
        d_o_data.append(d_i)
    return d_o_data


@csrf_exempt
def imgupload(request):
    if request.method == "POST":
        iu_data = request.FILES.get('file')
        iu_file = config.get('userimg', 'imgfile')
        file_name_list = os.listdir(iu_file)
        iu_old_name = iu_data.name
        iu_salt = ''.join(random.sample(string.ascii_letters + string.digits, 16))
        iu_img_name = iu_salt + '.' + iu_old_name.split('.').pop()
        iu_status = 1

        while iu_img_name in file_name_list:
            print('文件名称重复，重新生成')
            iu_salt = ''.join(random.sample(string.ascii_letters + string.digits, 16))
            iu_img_name = iu_salt + iu_old_name.split('.').pop()

        iu_img_file = os.path.join(iu_file, iu_img_name)
        fobj = open(iu_img_file, 'wb')
        for chrunk in iu_data.chunks():
            fobj.write(chrunk)
        fobj.close()
        iu_name = request.user
        iu_id = User.objects.filter(username=iu_name).values_list('id')[0][0]
        UserProfile.objects.filter(user_id=iu_id).update(imgfile=iu_img_name)
        iu_status = 0
        return HttpResponse(json.dumps({'status':iu_status, 'imgfile':iu_img_name}))







































def adduser():
    auser = User()

    #修改密码
    # auser = User.objects.get(username='jx_ops')
    # auser.set_password('JieXin#888888')
    # auser.save()

    #注册用户
    # auser = User.objects.create_user(username="jx_ops", password="JieXin#888888")
    # auser.save()
    # profile = UserProfile()
    # profile.user_id = auser.id
    # profile.permissions_page = 'all'
    # profile.save()